package com.skillworld.webapp.web.pages.rest.user;

import java.util.List;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.team.Team;
import com.skillworld.webapp.model.userservice.UserService;
import com.skillworld.webapp.model.util.InvalidArgumentException;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

@ContentType("text/xml")
public class TopTeams
{
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @SuppressWarnings("unused")
    @Property
    private List<Team> teams;
    
    @SuppressWarnings("unused")
    @Property
    private Team team;  // loop iterator
    
    @Inject
    private UserService userService;

    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private Request request;
   

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }

        String countParam = request.getParameter("count");
        
        if (countParam == null)
        {
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }

        try
        {
            int count = Integer.parseInt(countParam);    
            teams = userService.topTeams(count);
        }
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
        catch (InvalidArgumentException e) 
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
    }   
}
